/**
 * Created by Kuballle on 10/25/2014.
 */


function makeFacebookPhotoURL( id, accessToken ) {
    return 'https://graph.facebook.com/' + id + '/picture?access_token=' + accessToken;
}

function login( callback ) {
    FB.login(function(response) {
        if (response.authResponse) {
            //console.log('Welcome!  Fetching your information.... ');
            if (callback) {
                callback(response);
            }
        } else {
            console.log('User cancelled login or did not fully authorize.');
        }
    },{scope: 'email,user_likes,user_photos,user_friends,read_friendlists'} );
}

function getStatusConnect( callback ){
    FB.getLoginStatus(function(response){
        if (response.status === 'connected') {
            var uid = response.authResponse.userID,
                accessToken = response.authResponse.accessToken || '';
            callback([uid,accessToken]);
        } else if (response.status === 'not_authorized') {
            // the user is logged in to Facebook,
            // but has not authenticated your app
            login(function(loginResponse){
                console.log(loginResponse);
                var uid = loginResponse.authResponse.userID,
                    accessToken = loginResponse.authResponse.accessToken || '';
                callback([uid,accessToken]);
            });
        } else {
            // the user isn't logged in to Facebook.
            login(function(loginResponse){
                console.log(loginResponse);
                var uid = loginResponse.authResponse.userID,
                    accessToken = loginResponse.authResponse.accessToken || '';
                callback([uid,accessToken]);
            });
        }
    })
}

function getProfile( callback ){
    FB.api(
        '/me',
        function(albumResponse) {
            //console.log( ' got albums ' );
            if (callback) {
                callback(albumResponse);
            }
        }
    );
}

function getAlbums( callback ) {
    FB.api(
        '/me/albums',
        {fields: 'id,cover_photo'},
        function(albumResponse) {
            //console.log( ' got albums ' );
            if (callback) {
                callback(albumResponse);
            }
        }
    );

}

function getPhotosForAlbumId( albumId, callback ) {
    FB.api(
            '/'+albumId+'/photos',
        {fields: 'id'},
        function(albumPhotosResponse) {
            //console.log( ' got photos for album ' + albumId );
            if (callback) {
                callback( albumId, albumPhotosResponse );
            }
        }
    );
}

function getLikesForPhotoId( photoId, callback ) {
    FB.api(
            '/'+albumId+'/photos/'+photoId+'/likes',
        {},
        function(photoLikesResponse) {
            if (callback) {
                callback( photoId, photoLikesResponse );
            }
        }
    );
}

function logout( ){
    FB.logout(function(){
    });
}

function main(callback) {

    var allPhotos = [],
        profile = [];

    var accessToken = '';

    getStatusConnect(function(statusResponse){
        if(statusResponse[1] != ""){
            getProfile(function(profileResponse){
                var id = profileResponse.id,
                    email = profileResponse.email,
                    first_name = profileResponse.first_name,
                    gender = profileResponse.gender,
                    last_name = profileResponse.last_name,
                    link = profileResponse.link,
                    locale = profileResponse.locale,
                    name = profileResponse.name,
                    timezone = profileResponse.timezone;

                profile = [id,email,first_name,gender,last_name,link,locale,name,timezone];
//                callback( "", profile );
            });
            getAlbums(function(albumResponse) {
                var i, album, deferreds = {}, listOfDeferreds = [];

                for (i = 0; i < albumResponse.data.length; i++) {
                    album = albumResponse.data[i];
                    deferreds[album.id] = $.Deferred();
                    listOfDeferreds.push( deferreds[album.id] );
                    getPhotosForAlbumId( album.id, function( albumId, albumPhotosResponse ) {
                        var i, facebookPhoto;
                        for (i = 0; i < albumPhotosResponse.data.length; i++) {
                            facebookPhoto = albumPhotosResponse.data[i];
                            allPhotos.push({
                                'id'	:	facebookPhoto.id,
                                'added'	:	facebookPhoto.created_time,
                                'url'	:	makeFacebookPhotoURL( facebookPhoto.id, statusResponse[1] )
                            });
                        }
                        deferreds[albumId].resolve();
                    });
                }

                $.when.apply($, listOfDeferreds ).then( function() {
                    if (callback) {
                        callback( allPhotos, profile );
                    }
                }, function( error ) {
                    if (callback) {
                        callback( allPhotos, profile, error );
                    }
                });
            });
        }
    });

//    login(function(loginResponse) {
//        accessToken = loginResponse.authResponse.accessToken || '';
//
//        getProfile(function(profileResponse){
//            var id = profileResponse.id,
//                email = profileResponse.email,
//                first_name = profileResponse.first_name,
//                gender = profileResponse.gender,
//                last_name = profileResponse.last_name,
//                link = profileResponse.link,
//                locale = profileResponse.locale,
//                name = profileResponse.name,
//                timezone = profileResponse.timezone;
//
//            profile = [id,email,first_name,gender,last_name,link,locale,name,timezone];
//        });
//        getAlbums(function(albumResponse) {
//            var i, album, deferreds = {}, listOfDeferreds = [];
//
//            for (i = 0; i < albumResponse.data.length; i++) {
//                album = albumResponse.data[i];
//                deferreds[album.id] = $.Deferred();
//                listOfDeferreds.push( deferreds[album.id] );
//                getPhotosForAlbumId( album.id, function( albumId, albumPhotosResponse ) {
//                    var i, facebookPhoto;
//                    for (i = 0; i < albumPhotosResponse.data.length; i++) {
//                        facebookPhoto = albumPhotosResponse.data[i];
//                        allPhotos.push({
//                            'id'	:	facebookPhoto.id,
//                            'added'	:	facebookPhoto.created_time,
//                            'url'	:	makeFacebookPhotoURL( facebookPhoto.id, accessToken )
//                        });
//                    }
//                    deferreds[albumId].resolve();
//                });
//            }
//
//            $.when.apply($, listOfDeferreds ).then( function() {
//                if (callback) {
//                    callback( allPhotos, profile );
//                }
//            }, function( error ) {
//                if (callback) {
//                    callback( allPhotos, profile, error );
//                }
//            });
//        });
//    });
}

